package com.mrjy.maintain.bo;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.DistributorInfo;
import com.mrjy.common.entity.PartnerInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.AESUtil;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.MD5Encrypt;
import com.mrjy.common.util.RegexUtil;
import com.mrjy.common.util.UpdateDisableFlagUtil;
import com.mrjy.maintain.dao.IPartnerInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dto.DistributorTeamDto;
import com.mrjy.maintain.dto.PartnerInfoDTO;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dao.IDistributorTeamInfoDao;
import com.mrjy.share.dto.DistributorInfoDTO;

@Service("partnerInfoBo")
public class PartnerInfoBo implements IPartnerInfoBo {
	
	
	@Resource
	private IPartnerInfoDao partnerInfoDao;
	
	@Resource
	private IUserInfoDao userInfoDao;
	
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	
	@Resource
	private IDistributorTeamInfoDao distributorTeamInfoDao;
	
	
	@Override
	public Object txInsert(PartnerInfoDTO partnerInfo,HttpSession session) {
		Map<String,Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getPartnerName())) {
			map.put("err_code", 400);
			map.put("err_msg", "合作方名称不能为空");
			return map;
		}
		if (partnerInfo.getPartnerName().length()>16) {
			map.put("err_code", 401);
			map.put("err_msg", "合作方名称过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getMobilePhone())) {
			map.put("err_code", 402);
			map.put("err_msg", "手机号不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(partnerInfo.getMobilePhone()) && 
				!RegexUtil.checkMobile(partnerInfo.getMobilePhone())) {
			map.put("err_code", 403);
			map.put("err_msg", "手机号格式不正确");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getLoginCode())) {
			map.put("err_code", 404);
			map.put("err_msg", "账号不能为空");
			return map;
		}
		if (partnerInfo.getLoginCode().length()>16) {
			map.put("err_code", 405);
			map.put("err_msg", "账号过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getPasswordSrc())) {
			map.put("err_code", 406);
			map.put("err_msg", "密码不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(partnerInfo.getPasswordSrc()) && 
				!RegexUtil.checkPwd(partnerInfo.getPasswordSrc())) {
			map.put("err_code", 407);
			map.put("err_msg", "密码长度在6~18位之间，且只能包含字母、数字和下划线");
			return map;
		}
		if (!(partnerInfo.getSharingProportion()>0) &&
				!(partnerInfo.getSharingProportion()<1)) {
			map.put("err_code", 408);
			map.put("err_msg", "分成比例必须为0~1之间的小数");
			return map;
		}
		/*if (StringUtils.isBlank(partnerInfo.getBankCard())) {
			map.put("err_code", 409);
			map.put("err_msg", "银行卡号不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(partnerInfo.getBankCard()) && 
				!RegexUtil.checkICBC(partnerInfo.getBankCard())) {
			map.put("err_code", 410);
			map.put("err_msg", "银行卡格式不正确,请填写正确的工商银行卡号");
			return map;
		}*/
		if (StringUtils.isBlank(partnerInfo.getSignTimeString())) {
			map.put("err_code", 411);
			map.put("err_msg", "合同签订时间不能为空");
			return map;
		}
		if (partnerInfo.getContractValidYear() == null || partnerInfo.getContractValidYear() <= 0) {
			map.put("err_code", 412);
			map.put("err_msg", "请正确填写合同年限");
			return map;
		}
		
		UserInfo ui = userInfoDao.queryByLoginCode(partnerInfo.getLoginCode());
		if(ui != null){
			map.put("err_code", 204);
			map.put("err_msg", "该管理员账号已存在！");
			return map;
		}
		UserInfo existInfo = userInfoDao.queryByMobilePhone(partnerInfo.getMobilePhone());
		if(existInfo != null && existInfo.getRoleId().intValue() != RoleInfoEnum.STUDENT.getRoleId()
				&& existInfo.getRoleId().intValue() != RoleInfoEnum.SCHOOL_ADMIN.getRoleId()){//不是普通用户、学校管理员
			map.put("err_code", 205);
			map.put("err_msg", "该手机已经被其他角色（非普通用户、学校）使用，请换个手机号码试试");
			return map;
		}
		
		partnerInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
		partnerInfo.setDisableFlag(0);
		partnerInfo.setPassword(AESUtil.encrypt(AESUtil.getRawKey(AESUtil.PRIMARY_KEY.getBytes()), partnerInfo.getPasswordSrc()));
		if(StringUtils.isNotBlank(partnerInfo.getSignTimeString())){
			SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
			try {
				Date d = sdf.parse(partnerInfo.getSignTimeString());
				partnerInfo.setSignTime(new Timestamp(d.getTime()));
				if(partnerInfo.getContractValidYear() > 0){
					partnerInfo.setDeadlineTime(new Timestamp(DateUtil.dateTimeAddYears(d.getTime(), partnerInfo.getContractValidYear())));
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
        //操作user_info表,distributor_info表
        int row =0;
		DistributorInfo dInfo = new DistributorInfo();
		if(existInfo != null ){//是普通用户和学校，则实现绑定
			if(existInfo.getRoleId().intValue() == RoleInfoEnum.STUDENT.getRoleId()){//普通-->合作方
				existInfo.setRoleId(RoleInfoEnum.PARTNER_ADMIN.getRoleId());
			}else if(existInfo.getRoleId().intValue() == RoleInfoEnum.SCHOOL_ADMIN.getRoleId()){//学校-->合作方&学校管理
				existInfo.setRoleId(RoleInfoEnum.PARTNER_SCHOOL_ADMIN.getRoleId());
			}
			if(StringUtils.isBlank(existInfo.getRecommendCode())){
				existInfo.setRecommendCode(userInfoDao.generateRecommendCodeOne(8));
			}
			existInfo.setBankCard(partnerInfo.getBankCard());
			existInfo.setLoginCode(partnerInfo.getLoginCode());
			existInfo.setPassword(MD5Encrypt.encryptByMD5(partnerInfo.getPasswordSrc()));
			row = userInfoDao.updateById(existInfo);
			
			dInfo.setUserId(existInfo.getId());
			dInfo.setShareCode(existInfo.getRecommendCode());
			partnerInfo.setUserId(existInfo.getId());
		}else{//直接新建合作方
			String recommendCode = userInfoDao.generateRecommendCodeOne(8) ;
			UserInfo info = new UserInfo();
			info.setBankCard(partnerInfo.getBankCard());
			info.setUserName(partnerInfo.getPartnerName());
			info.setLoginCode(partnerInfo.getLoginCode());
			info.setPassword(MD5Encrypt.encryptByMD5(partnerInfo.getPasswordSrc()));
			info.setRoleId(RoleInfoEnum.PARTNER_ADMIN.getRoleId());//9--合作方管理员
			info.setDisableFlag(0);
			info.setPartnerId(partnerInfo.getId());
			info.setRegisterDate(new Date().getTime());
			info.setRecommendCode(recommendCode);
			info.setMobilePhone(partnerInfo.getMobilePhone());
			row = userInfoDao.insert(info);
			
			dInfo.setUserId(info.getId());
			dInfo.setShareCode(recommendCode);
			partnerInfo.setUserId(info.getId());
		}
		int count = partnerInfoDao.insert(partnerInfo);
		if (count > 0) {//返回插入后的id
			if(row == 1){
				dInfo.setDistributorName(partnerInfo.getPartnerName());
				dInfo.setMobilePhone(partnerInfo.getMobilePhone());
				dInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
				dInfo.setDistributorType("3");
				dInfo.setSharingProportion(partnerInfo.getSharingProportion());
				dInfo.setBankCard(partnerInfo.getBankCard());
				dInfo.setDisabledFlag(0);
				dInfo.setUpgradeTime(partnerInfo.getSignTime());
				dInfo.setDeadlineTime(partnerInfo.getDeadlineTime());
				distributorInfoDao.insert(dInfo); 
			}
			
			map.put("err_code", 200);
			map.put("err_msg", "插入成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "插入失败");
		}
		return map;
	}

	@Override
	public Object queryByUserId(int userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		PartnerInfoDTO dto = partnerInfoDao.queryByUserId(userId);
		if(dto !=null){
			dto.setPasswordSrc(AESUtil.decrypt(dto.getPassword(), AESUtil.getRawKey(AESUtil.PRIMARY_KEY.getBytes())));
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", dto);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "查询无数据");
		}
		return map;
	}

	@Override
	public Object txUpdateById(PartnerInfoDTO partnerInfo,HttpSession session) {
		Map<String,Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getPartnerName())) {
			map.put("err_code", 400);
			map.put("err_msg", "合作方名称不能为空");
			return map;
		}
		if (partnerInfo.getPartnerName().length()>16) {
			map.put("err_code", 401);
			map.put("err_msg", "合作方名称过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getMobilePhone())) {
			map.put("err_code", 402);
			map.put("err_msg", "手机号不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(partnerInfo.getMobilePhone()) && 
				!RegexUtil.checkMobile(partnerInfo.getMobilePhone())) {
			map.put("err_code", 403);
			map.put("err_msg", "手机号格式不正确");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getLoginCode())) {
			map.put("err_code", 404);
			map.put("err_msg", "账号不能为空");
			return map;
		}
		if (partnerInfo.getLoginCode().length()>16) {
			map.put("err_code", 405);
			map.put("err_msg", "账号过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isBlank(partnerInfo.getPasswordSrc())) {
			map.put("err_code", 406);
			map.put("err_msg", "密码不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(partnerInfo.getPasswordSrc()) && 
				!RegexUtil.checkPwd(partnerInfo.getPasswordSrc())) {
			map.put("err_code", 407);
			map.put("err_msg", "密码长度在6~18位之间，且只能包含字母、数字和下划线");
			return map;
		}
		if (!(partnerInfo.getSharingProportion()>0) &&
				!(partnerInfo.getSharingProportion()<1)) {
			map.put("err_code", 408);
			map.put("err_msg", "分成比例必须为0~1之间的小数");
			return map;
		}
		/*if (StringUtils.isBlank(partnerInfo.getBankCard())) {
			map.put("err_code", 409);
			map.put("err_msg", "银行卡号不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(partnerInfo.getBankCard()) && 
				!RegexUtil.checkICBC(partnerInfo.getBankCard())) {
			map.put("err_code", 410);
			map.put("err_msg", "银行卡格式不正确,请填写正确的工商银行卡号");
			return map;
		}*/
		if (StringUtils.isBlank(partnerInfo.getSignTimeString())) {
			map.put("err_code", 411);
			map.put("err_msg", "合同签订时间不能为空");
			return map;
		}
		if (partnerInfo.getContractValidYear() == null || partnerInfo.getContractValidYear() <= 0) {
			map.put("err_code", 412);
			map.put("err_msg", "请正确填写合同年限");
			return map;
		}
	
		partnerInfo.setPassword(AESUtil.encrypt(AESUtil.getRawKey(AESUtil.PRIMARY_KEY.getBytes()), partnerInfo.getPasswordSrc()));
		PartnerInfoDTO mPartner =  partnerInfoDao.queryByUserId(partnerInfo.getUserId());
		if(mPartner != null && !mPartner.getMobilePhone().equals(partnerInfo.getMobilePhone())){
			UserInfo existInfo = userInfoDao.queryByMobilePhone(partnerInfo.getMobilePhone());
			if(existInfo != null ){//已被使用
				map.put("err_code", 3);
				map.put("err_msg", "该手机已经被使用，请换个手机号码试试");
				return map;
			}	
		}
		
		boolean updateFlag = false;
		PartnerInfo pInfo = partnerInfoDao.queryById(partnerInfo.getId());
		if(StringUtils.isNotBlank(partnerInfo.getSignTimeString())){
			SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
			try {
				Date d = sdf.parse(partnerInfo.getSignTimeString());
				partnerInfo.setSignTime(new Timestamp(d.getTime()));
				if(partnerInfo.getContractValidYear() > 0){
					partnerInfo.setDeadlineTime(new Timestamp(DateUtil.dateTimeAddYears(d.getTime(), partnerInfo.getContractValidYear())));
					updateFlag = true;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else{
			if(partnerInfo.getContractValidYear()!=pInfo.getContractValidYear() && partnerInfo.getContractValidYear() > 0){
				partnerInfo.setDeadlineTime(new Timestamp(DateUtil.dateTimeAddYears(pInfo.getSignTime().getTime(), partnerInfo.getContractValidYear())));
			}
		}
		
		int count = partnerInfoDao.updateById(partnerInfo);
		if (count == 1) {
			UserInfo info = userInfoDao.queryByIdForBack(partnerInfo.getUserId()); //管理员信息
			if(info != null){
				info.setLoginCode(partnerInfo.getLoginCode());
				info.setPassword(MD5Encrypt.encryptByMD5(partnerInfo.getPasswordSrc()));
				info.setUserName(partnerInfo.getPartnerName());
				info.setBankCard(partnerInfo.getBankCard());
				userInfoDao.updateById(info);
				
				if(updateFlag){
					//更新推广者表的有效期
					Map<String,Object> paramMap = new HashMap<String,Object>();
					paramMap.put("userId", info.getId());
					paramMap.put("disabledFlag", 0);
					paramMap.put("distributorTypes", new String[]{"3"});
					List<DistributorInfoDTO> dInfoList = distributorInfoDao.queryByMap(paramMap);
					if(dInfoList != null && dInfoList.size() > 0){
						DistributorInfo dInfo = new DistributorInfo();
						dInfo.setId(dInfoList.get(0).getId());
						dInfo.setDeadlineTime(partnerInfo.getDeadlineTime());
						dInfo.setDistributorName(partnerInfo.getPartnerName());
						distributorInfoDao.updateById(dInfo);
					}
				}
				
			}
			
			
			
			map.put("err_code", 200);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public int txDeleteByIds(int[] ids) {
		try {
			return partnerInfoDao.deleteByIds(ids);
		} catch (DataAccessException e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public Object txUpdateDisableFlag(PartnerInfo partnerInfo,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (partnerInfo.getIds()==null||partnerInfo.getIds().length==0) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
		int count = partnerInfoDao.updateDisableFlag(partnerInfo);
		if (count > 0 ) {
			PartnerInfo pInfo = null;
			UserInfo ui = null;
			for (Integer id : partnerInfo.getIds()) {
				
				//操作user表
				pInfo = partnerInfoDao.queryById(id);
				ui = userInfoDao.queryById(pInfo.getUserId());
				if (partnerInfo.getDisableFlag().intValue()==0) {
					ui.setRoleId(RoleInfoEnum.PARTNER_ADMIN.getRoleId());
				}
				if (partnerInfo.getDisableFlag().intValue()==1) {
					ui.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
				}
				userInfoDao.updateById(ui);
				
				//操作推广身份信息
				String[] distributorTypes = {"3"};
				UpdateDisableFlagUtil.updateDisableFlagForTeam(distributorTypes,
						pInfo.getUserId(), partnerInfo.getDisableFlag());
			}
			map.put("err_code", 200);
			map.put("err_msg", "操作成功,"+count+"条记录受影响");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+count+"条记录受影响");
		}
		return map;
	}

	@Override
	public Object queryListPage(PartnerInfoDTO dto,HttpSession session) {
		Map<String,Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<PartnerInfoDTO> list = new ArrayList<PartnerInfoDTO>();
		//全站合作方数量
		PartnerInfoDTO dto2 = new PartnerInfoDTO();
//		int totalCount = partnerInfoDao.queryCountListPage(dto2);

        int total = partnerInfoDao.queryCountListPage(dto);
		if (total  > 0) {
			list =  partnerInfoDao.queryListPage(dto);
			for(PartnerInfoDTO info : list){
				info.setPasswordSrc(AESUtil.decrypt(info.getPassword(), AESUtil.getRawKey(AESUtil.PRIMARY_KEY.getBytes())));
			}
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
			map.put("total", total);
            map.put("totalCount", total);
        }else {
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("rows", list);
			map.put("total", total);
            map.put("totalCount", total);
        }
		return map;
		
	}

	@Override
	public Object txCheckPartnerInfoStatusExpired() {
		Map<String,Object> map = new HashMap<String,Object>();
		List<PartnerInfoDTO> expireList = partnerInfoDao.queryExpirePartnerInfo();
		if(expireList != null && expireList.size() > 0){
			int updateCount = 0;
			PartnerInfo pi = null;
			PartnerInfoDTO pDto = null;
			UserInfo ui = null;
			for(PartnerInfoDTO dto : expireList){
				pDto.setId(dto.getId());
				pDto.setDisableFlag(1);
				int row = partnerInfoDao.updateById(pDto);
				if(row == 1){
					//操作user表
					pi = partnerInfoDao.queryById(pi.getId());
					ui = userInfoDao.queryById(dto.getUserId());
					ui.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
					userInfoDao.updateById(ui);
					
					//操作推广身份信息
					String[] distributorTypes = {"3"};
					UpdateDisableFlagUtil.updateDisableFlagForTeam(distributorTypes,
							dto.getUserId(), 1);
					
					updateCount ++;
				}
			}
			map.put("err_code", 0);
			map.put("err_msg", "成功更新了"+ updateCount + "个合作方");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "没有过期的合作方更新");
		}
		return map;
	}

	@Override
	public Object queryPageDistTeam(PartnerInfoDTO dto) {
		Map<String, Object> map = new HashMap<String, Object>();
		int total = partnerInfoDao.countPageDistTeam(dto.getUserId());
		if(total > 0){
			List<DistributorTeamDto> list = partnerInfoDao.queryPageDistTeam(dto);
			if(null !=list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
				map.put("total", total);
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "查询无数据");
			}
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "查询无数据");
		}
		return map;
	}

	@Override
	public Object exportExl(PartnerInfoDTO dto, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<PartnerInfoDTO> dataset = partnerInfoDao.queryListPage(dto);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		for(PartnerInfoDTO info : dataset){
			info.setPasswordSrc(AESUtil.decrypt(info.getPassword(), AESUtil.getRawKey(AESUtil.PRIMARY_KEY.getBytes())));
		}
		try {
			ExcelUtil.writeExcel(response, "合作方"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, PartnerInfoDTO.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

}
